import 'package:flutter/material.dart';
import 'package:keyboard_actions/keyboard_actions.dart';

/// 本项目通用的布局（SingleChildScrollView）
/// 1.底部存在按钮
/// 2.底部没有按钮
class HkScrollView extends StatelessWidget {
  /// 注意：同时存在底部按钮与keyboardConfig配置时，为保证软键盘弹出高度正常。需要在`Scaffold`使用 `resizeToAvoidBottomInset: defaultTargetPlatform != TargetPlatform.iOS,`
  /// 除非Android与iOS平台均使用keyboard_actions
  const HkScrollView({
    Key? key,
    @required this.children,
    this.padding,
    this.physics = const BouncingScrollPhysics(),
    this.crossAxisAlignment = CrossAxisAlignment.start,
    this.bottomButton,
    this.keyboardConfig,
    this.tapOutsideToDismiss = false,
    this.overScroll = 16.0,
    this.keyboardDisabledColor = Colors.grey,
    this.keyboardIconTheme,
    this.controller,
  }) : super(key: key);

  final List<Widget>? children;
  final EdgeInsetsGeometry? padding;
  final ScrollPhysics physics;
  final CrossAxisAlignment crossAxisAlignment;
  final Widget? bottomButton;
  final KeyboardActionsConfig? keyboardConfig;
  final Color? keyboardDisabledColor;
  final IconThemeData? keyboardIconTheme;

  /// 注意，此时keyBoardConfig必须设置为null
  final ScrollController? controller;

  /// 键盘外部按下将其关闭
  final bool tapOutsideToDismiss;

  /// 默认弹起位置在TextField的文字下面，可以添加此属性继续向上滑动一段距离。用来露出完整的TextField。
  final double overScroll;

  @override
  Widget build(BuildContext context) {
    Widget contents = Column(
      crossAxisAlignment: crossAxisAlignment,
      children: children ?? [],
    );

    if (keyboardConfig != null) {
      /// iOS&Android 键盘处理
      if (padding != null) {
        contents = Padding(
            padding: padding ?? EdgeInsetsGeometry.infinity, child: contents);
      }

      contents = Theme(
          data: Theme.of(context).copyWith(
              disabledColor: keyboardDisabledColor,
              iconTheme: keyboardIconTheme ??
                  IconTheme.of(context).copyWith(
                    color: Theme.of(context).primaryColor,
                    size: 30,
                  )),
          child: KeyboardActions(
              tapOutsideBehavior: TapOutsideBehavior.opaqueDismiss,
              isDialog: bottomButton != null,
              overscroll: overScroll,
              config: keyboardConfig ?? const KeyboardActionsConfig(),
              tapOutsideToDismiss: tapOutsideToDismiss,
              child: contents));
    } else {
      contents = SingleChildScrollView(
        padding: padding,
        physics: physics,
        child: contents,
        controller: controller,
      );
    }

    if (bottomButton != null) {
      contents = Column(
        children: <Widget>[
          Expanded(child: contents),
          SafeArea(child: bottomButton ?? Container())
        ],
      );
    }

    return contents;
  }
}
